<!-- eslint-disable unused-imports/no-unused-vars -->
<script setup lang="ts">
import type { ResumeListItem } from "../apis/type"
import { Edit } from "@element-plus/icons-vue"
import { ElButton, ElMessageBox } from "element-plus"
import { computed, defineOptions, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"
import { useRouter } from "vue-router"
import { useResumeStore } from "@/pinia/stores/resume"

defineOptions({ name: "ResumeList" })

const props = withDefaults(defineProps<{
  items: ResumeListItem[]
  loading: boolean
  total: number
  maxWidth?: number
  selectedId?: number | null
}>(), {
  items: () => [],
  selectedId: null
})

const emit = defineEmits<{
  (e: "select", item: ResumeListItem): void
  (e: "loadMore"): void
}>()

const resumeStore = useResumeStore()
const router = useRouter()

const paneStyle = computed(() => ({
  maxWidth: `${props.maxWidth ?? 240}px`
}))

const hasMore = computed(() => (props.items?.length || 0) < props.total)

const wrapRef = ref<HTMLElement | null>(null)
const sentinelRef = ref<HTMLElement | null>(null)
let io: IntersectionObserver | null = null
let observedEl: HTMLElement | null = null
let ioLock = false

// 滚动加载更多
async function tryLoadMore() {
  if (ioLock) return
  if (props.loading || !hasMore.value) return
  ioLock = true
  emit("loadMore")
  await nextTick()
  ioLock = false
}

// 设置交叉观察器
function setupObserver() {
  teardownObserver()
  io = new IntersectionObserver(
    (entries) => {
      const entry = entries[0]
      if (entry?.isIntersecting) {
        tryLoadMore()
      }
    },
    {
      root: wrapRef.value ?? null,
      rootMargin: "300px 0px 0px 0px",
      threshold: 0
    }
  )
  refreshObserver()
}

// 刷新观察器
function refreshObserver() {
  if (!io) return
  if (observedEl) {
    io.unobserve(observedEl)
    observedEl = null
  }
  if (sentinelRef.value && hasMore.value) {
    io.observe(sentinelRef.value)
    observedEl = sentinelRef.value
  }
}

// 清理观察器
function teardownObserver() {
  if (io) {
    if (observedEl) {
      io.unobserve(observedEl)
      observedEl = null
    }
    io.disconnect()
    io = null
  }
}

// 格式化时间
function formatTime(timeStr?: string) {
  if (!timeStr) return ""
  return new Date(timeStr).toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit"
  })
}

// 处理编辑简历
function handleEditResume(resumeId: number) {
  router.push({
    path: `/internship/resume/edit/${resumeId}`
  })
}

// 处理删除简历
async function handleDeleteResume(resume: ResumeListItem) {
  try {
    await ElMessageBox.confirm(
      `确定要删除简历「${resume.resumeName}」吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    )

    await resumeStore.removeResume(resume.resumeId)
  } catch (error) {
    // 取消删除时不做处理
  }
}

// 处理设置默认简历已移至详情页面

// 组件挂载时设置观察器
onMounted(() => {
  setupObserver()
})

// 监听数据变化，刷新观察器
watch(
  () => [(props.items?.length || 0), props.total, props.loading],
  () => nextTick(refreshObserver)
)

// 组件卸载时清理观察器
onBeforeUnmount(() => {
  teardownObserver()
})
</script>

<template>
  <div class="pane-left" ref="wrapRef" :style="paneStyle">
    <div class="list">
      <el-skeleton v-if="loading && (!items || items.length === 0)" :rows="6" animated />

      <div
        v-for="item in items"
        :key="item.resumeId"
        class="list-item"
        :class="{ selected: selectedId === item.resumeId }"
        @click="emit('select', item)"
      >
        <div class="item-header">
          <div class="title-container">
            <div class="title">
              {{ item.resumeName }}
            </div>
            <el-tag
              v-if="item.isDefault === 1"
              size="small"
              type="primary"
              class="default-tag"
            >
              默认
            </el-tag>
          </div>
          <div class="status-tag" :class="{ active: item.status === '正常' }">
            {{ item.status }}
          </div>
        </div>
        <div class="meta">
          <span class="create-time">
            创建时间：{{ formatTime(item.createTime) }}
          </span>
        </div>
        <div class="meta">
          <span class="update-time">
            更新时间：{{ formatTime(item.updateTime) }}
          </span>
        </div>
        <div class="item-footer">
          <ElButton type="text" size="small" @click.stop="handleEditResume(item.resumeId)" :icon="Edit">
            编辑
          </ElButton>
          <ElButton type="text" size="small" @click.stop="handleDeleteResume(item)" danger>
            删除
          </ElButton>
        </div>
      </div>

      <div ref="sentinelRef" class="sentinel" />

      <div class="list-footer">
        <span v-if="loading">加载中...</span>
        <span v-else-if="!hasMore">没有更多了</span>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.pane-left {
  background: #fff;
  border: 1px solid #eef2f7;
  border-radius: 12px;
  padding: 12px;
  overflow: auto;
  max-height: calc(100vh - 180px);
  width: 100%;
}

.list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.list-item {
  border: 1px solid #eef2f7;
  border-radius: 12px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
  background-color: #fff;

  &:hover {
    border-color: #cdd6e1;
    box-shadow: 0 2px 10px rgba(16, 24, 40, 0.06);
    transform: translateY(-1px);
  }

  &.selected {
    border-color: #3b82f6;
    background-color: #f0f9ff;
    box-shadow: 0 2px 10px rgba(59, 130, 246, 0.15);

    .item-header {
      .title-container .title {
        color: #3b82f6;
        font-weight: 700;
      }
    }
  }
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.title-container {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.default-tag {
  height: 20px;
  line-height: 20px;
}

.status-tag {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #ef4444;
  color: #fff;
}

.status-tag.active {
  background-color: #10b981;
}

.meta {
  color: #6b7280;
  font-size: 13px;
  margin-bottom: 8px;
}

.position-info {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.info-tag {
  background-color: #f0f9ff;
  color: #38bdf8;
  border: 1px solid #e0f2fe;
  border-radius: 999px;
  padding: 2px 8px;
  font-size: 12px;
}

.info-tag.disabled {
  background-color: #f9fafb;
  color: #9ca3af;
  border: 1px solid #f3f4f6;
}

.item-footer {
  display: flex;
  gap: 8px;
  border-top: 1px solid #f3f4f6;
  padding-top: 8px;
}

.item-footer .el-button {
  padding: 0;
  height: auto;
  font-size: 12px;
}

.list-footer {
  text-align: center;
  color: #6b7280;
  padding: 8px 0 0;
}

.sentinel {
  height: 1px;
}

// 增强滚动条样式
.pane-left::-webkit-scrollbar {
  width: 6px;
}

.pane-left::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.pane-left::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  transition: background 0.2s;
}

.pane-left::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

// 添加对Firefox的支持
.pane-left {
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}
</style>
